<template>
  <div :class="{ show: isShow }" class="header-search">
    <SvgIconComponent
        class-name="search-icon"
        icon="search"
        @click.stop="onShowClick"
    />
    <el-select
        ref="headerSearchSelectRef"
        v-model="search"
        :remote-method="querySearch"
        class="header-search-select"
        default-first-option
        filterable
        placeholder="Search"
        remote
        @change="onSelectChange"
    >
      <el-option
          v-for="option in searchOptions"
          :key="option.item.path"
          :label="option.item.name"
          :value="option.item"
      ></el-option>
    </el-select>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import SvgIconComponent from "@/pageShows/SvgIconComponent/SvgIconComponent.vue";
import Fuse from 'fuse.js'
import {useRouter} from 'vue-router'

let router = useRouter()
console.log(router.getRoutes())
let objRoutes = router.getRoutes()
let result = []
objRoutes.forEach(item => {
  let title = item.name
  let path = item.path
  result.push({title, path})
})
console.log(result)
/**
 * 搜索库相关
 */
const useFuseData = new Fuse(objRoutes, {
  shouldSort: true,
  minMatchCharLength: 1,
  keys: [
    {name: 'title', weight: 0.7},
    {name: 'path', weight: 0.3}
  ]
})
// console.log(useFuseData.search('D'), '-')
// 控制 search 显示
const isShow = ref(true)
// el-select 实例
const headerSearchSelectRef = ref(null)
const onShowClick = () => {
  isShow.value = !isShow.value
  headerSearchSelectRef.value.focus()
}

// search 相关
const search = ref('')
// 搜索结果
const searchOptions = ref([])
// 搜索方法
const querySearch = query => {
  if (query !== '') {
    searchOptions.value = useFuseData.search(query)
  } else {
    searchOptions.value = []
  }
}
// 选中回调
const onSelectChange = (item) => {
  console.log('onSelectChange', item.path)
  router.push(item.path)
}
</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;

  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }

  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    ::v-deep .el-input__inner {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      border-bottom: 1px solid #d9d9d9;
      vertical-align: middle;
    }
  }

  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>
